package com.zswl.bus.login;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.zswl.bus.Constant;
import com.zswl.bus.LogUtil;
import com.zswl.bus.MainActivity;
import com.zswl.bus.R;
import com.zswl.bus.RxUtil;
import com.zswl.bus.ShareUtils;
import com.zswl.bus.SpUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * 登录页
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {

    TextView tvProtocol;
    TextView tvPhone;
    TextView tvCode;
    private String protocol = "*登录即代表您同意《用户服务协议》";

    public static void startMe(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        SpUtil.init(context);
        return R.layout.activity_login;
    }

    @Override
    protected void init() {
        tvProtocol = findViewById(R.id.tv_protocol);
        tvPhone = findViewById(R.id.tv_phone);
        tvCode = findViewById(R.id.tv_code);


        SpannableString spannableString = new SpannableString(protocol);
        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                ProtocolActivity.startMe(context);
            }

            @Override
            public void updateDrawState(TextPaint ds) {
//                super.updateDrawState(ds);
                ds.setUnderlineText(false);
            }
        };

        spannableString.setSpan(clickableSpan, 9, protocol.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        spannableString.setSpan(new ForegroundColorSpan(Color.WHITE), 9, protocol.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvProtocol.setMovementMethod(LinkMovementMethod.getInstance());
        tvProtocol.setText(spannableString);

        if (!TextUtils.isEmpty(SpUtil.getUserId())) {
            MainActivity.startMe(context);
            finish();
        }
        JPushInterface.init(context);
        findViewById(R.id.tv_login).setOnClickListener(this);
    }


    /**
     * 登录
     */
    private void login() {

        String number = tvPhone.getText().toString().trim();
        String code = tvCode.getText().toString().trim();
        if (TextUtils.isEmpty(number) || TextUtils.isEmpty(code)) {
            Toast.makeText(context, "手机号或者密码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        api.userLogin(number, code).compose(RxUtil.io_main_nolife()).
                subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.i("sdf",d.getClass().toString());
                    }

                    @Override
                    public void onNext(String s) {
                        try {
                            JSONObject object = new JSONObject(s);
                            String msg = object.getString("msg");
                            String code = object.getString("code");
                            if ("0".equals(code)) {
                                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
                                return;
                            }
                            String data = object.getString("data");
                            SpUtil.putValue(Constant.USERID, data);
                            if (!TextUtils.isEmpty(s)) {
                                setAlias(data);
                                MainActivity.startMe(context);
                                finish();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.i("sdf",e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }


                });

    }

    private static final int MSG_SET_ALIAS = 1001;

    private void setAlias(String id) {
        String alias = id;

        // 调用 Handler 来异步设置别名
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, alias));
    }


    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    // 延迟 60 秒来调用 Handler 设置别名
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
            }

            LogUtil.d(logs);
        }
    };

    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    // 调用 JPush 接口来设置别名。
                    JPushInterface.setAliasAndTags(getApplicationContext(),
                            (String) msg.obj,
                            null,
                            mAliasCallback);
                    break;
                default:
            }
        }
    };


    @Override
    public void onClick(View v) {
        login();
    }
}
